/***
 * 对表格控件的一些封装
 * @param $
 */
(function($){
	
	/**
	 * 特殊化搜索表格树（强制第一列为展开列，绑定id为searchId的搜索框keyup事件，需要有主键：key=true）
	 * 需引入工具类
	 * <script language="javascript" type="text/javascript" src="tt/pub/bizjs/commonUtil.js"></script>
	 */
	SearchTree = {
			getOptions:function(){
				return {
					searchId : "txtNoteSearch",
					treeId : "tblNoteTree",
					datatype: "local",
//			        caption: "this is treeGrid Demo ", //标题可为空
					height:"500",
					width:"200",
			        colModel: [],
					hidegrid:false,
					hideHead:true,
					onSelectRow:null,
					searchFuncDelay:500,
					isTriggerSearch:true,//搜索是否触发选中事件
					withAdjust:false,//是否留有调整列空间
					searchTip:'',//搜索提示
					viewrecords:false,
					tree:{
						ExpandColumn:"id",
//						ExpandColClick:true
//		 				viewtreerecords : false,
//						treerecordtext : "{0} - {1}",
						ExpandColClick : true,
						checkChildren : false
					},
					treeData:[]
				};
			},
			moveUp:function(item){
				if(!item){
					item = window[this.options.treeId].getSelectedRow();
				}
				var parentId = item.parent;
				var $currRow = $("#" + item[this.keyCol]);
				var $prevRow = $currRow.prev();
				var prevItem = window[this.options.treeId].getRowData($prevRow.prop('id'));
				if(prevItem[this.keyCol]!=parentId){
					$currRow.after($prevRow);
					return prevItem;
				}
				return null;
			},
			moveDown:function(item){
				if(!item){
					item = window[this.options.treeId].getSelectedRow();
				}
				var parentId = item.parent;
				var $currRow = $("#" + item[this.keyCol]);
				var $nextRow = $currRow.next();
				var nextItem = window[this.options.treeId].getRowData($nextRow.prop('id'));
				if(nextItem.parent==parentId){
					$currRow.before($nextRow);
					return nextItem;
				}
				return null;
			},
			triggerFunc:function(func,delay){
				if($.isFunction(func)){
					if(!delay){
						delay=0;
					}
					for(var i in this.triggerIdMap){
						clearTimeout(i);
					}
					this.triggerIdMap={};
					var selId = this.selectId;
					var searchId = this.options.searchId;
					var $searchTxt = $('#'+searchId);
					if(selId){
						var t = setTimeout(function(){
								func(selId);
								$searchTxt.focusEnd();
							}, delay);
						this.triggerIdMap[t] = true;
					}
				}
			},
			/**
			 *  @param {String} position 新增行的位置,可以为first,last,after,before;默认last
			 * 	@param {String|Number} srcRowid 新增行位置的参考值
			 */
			addRowSpecial:function(item,parentId,flag,position, srcRowid){
				if(!parentId){
					return ;
				}
				var treeId = this.options.treeId;
				var $tbl = $('#'+treeId);
				window[treeId].addTreeNode(item,parentId,flag);
				if(!position){
					//默认last不需要额外操作 
					position = 'last';
				}
				if(position == 'first'){
					$('#'+parentId,$tbl).after($('#'+item.NODE_ID,$tbl));
				}
				if(!srcRowid){
					return ;
				}
				if(position == 'after'){
					$('#'+srcRowid,$tbl).after($('#'+item.NODE_ID,$tbl));
				}
				if(position == 'before'){
					$('#'+srcRowid,$tbl).before($('#'+item.NODE_ID,$tbl));
				}
			},
			init:function(options){
				var self = this;
				//触发点击事件全局变量
				this.triggerIdMap={};
				//初始化树参数
				this.options = $.extend(true,this.getOptions(),options);
				var expandName = options.colModel[0].name;
 				this.options.tree.ExpandColumn = expandName;
 				var keyCol="id";
 				$.each(options.colModel,function(i,obj){
 					if(obj.key){
 						keyCol = obj.name;
 					}
 				});
 				this.keyCol = keyCol;
				if(!options.colModel[0].width){
					this.options.colModel[0].width = options.width;
				}
				new ZTEsoftGrid(this.options.treeId).init(this.options).loadData(this.options.treeData);//可以是当前页数据,也可以是所有数据,屏蔽客户端/服务端分页
				//隐藏表头
				if(this.options.hideHead){
					$("#gview_"+this.options.treeId).find(".ui-jqgrid-hdiv").hide();
				}
				if(!this.options.withAdjust){
					$('#'+this.options.treeId).width($('#gview_'+this.options.treeId).width());
				}
				//防止出现双重纵向滚动条
				$('div.ui-jqgrid-bdiv').css('overflow-y','hidden');
				var $searchTxt = $("#"+this.options.searchId);
				if(this.options.searchTip){
					$searchTxt.searchTip(this.options.searchTip);
				}
				var treeObj = window[this.options.treeId];
				$searchTxt.bind("keyup",function(e){
					var textValueSrc = $searchTxt.val();
					var textValue = textValueSrc ? textValueSrc.toLowerCase():'';
					var data = treeObj.getRowData();
					var flag=false;
					var parents = '';
						if(e && e.keyCode===13){
							var isNext=false;
							var firstRowid ='';
							for(var i=0;i<data.length;i++){
								if(data[i][expandName].toLowerCase().indexOf(textValue)>=0){
									if(!firstRowid) {
										firstRowid = data[i][keyCol];
									}
									if(isNext === true ){
										if(!treeObj.isNodeVisible(data[i])){
											parents = treeObj.getNodeParentCascade(data[i]) ;
											for(var j = 0 ; j < parents.length ; j++ ){
												treeObj.expandNode(parents[j],false);
											}
										}
										treeObj.setSelectedRow(data[i][keyCol],false);
										flag=true;
										break;
									}
									if(treeObj.getSelectedRowid()==data[i][keyCol]){
										isNext = true;
									}
								}
							}
							isNext = false;
							if(!flag){
								treeObj.setSelectedRow(firstRowid,false);
							}
						}else{
							for(var i=0;i<data.length;i++){
								if(data[i][expandName].toLowerCase().indexOf(textValue)>=0){
									if(!treeObj.isNodeVisible(data[i])){
										parents = treeObj.getNodeParentCascade(data[i]);
										for(var j = 0 ; j < parents.length ; j++ ){
											treeObj.expandNode(parents[j],false);
										}
									}
									treeObj.setSelectedRow(data[i][keyCol],false);
									flag=true;
									break;
								}
							}
							if(!flag){
								treeObj.resetSelectedRow();
							}
						}
						self.selectId = treeObj.getSelectedRowid();
						if(self.options.isTriggerSearch){
							self.triggerFunc(self.options.onSelectRow,self.options.searchFuncDelay);
						}
					});
			}
	};
	BasicGrid ={
			getOptions:function(){
				return {
					tableData:[],
					tableId:'basicGridTableId',
					datatype: "local",
					height:"200",
					width:"200",
			        colModel: [],
					onSelectRow:null,
					withAdjust:true,//是否留有调整列空间
					viewrecords:false
				};
			},
			moveUp:function(item){
				if(!item){
					item = window[this.options.tableId].getSelectedRow();
				}
				var $currRow = $("#" + item[this.keyCol]);
				var $prevRow = $currRow.prev('.ui-widget-content');
				var prevItem = window[this.options.tableId].getRowData($prevRow.prop('id'));
				if($prevRow.length >0){
					$currRow.after($prevRow);
					return prevItem;
				}
				return null;
			},
			moveDown:function(item){
				if(!item){
					item = window[this.options.tableId].getSelectedRow();
				}
				var $currRow = $("#" + item[this.keyCol]);
				var $nextRow = $currRow.next('.ui-widget-content');
				var nextItem = window[this.options.treeId].getRowData($nextRow.prop('id'));
				if($nextRow.length >0){
					$currRow.before($nextRow);
					return nextItem;
				}
				return null;
			},
			init:function(options){
				this.options = $.extend(true,this.getOptions(),options);
 				var keyCol='';
 				$.each(this.options.colModel,function(i,obj){
 					if(obj.key){
 						keyCol = obj.name;
 					}
 				});
 				this.keyCol = keyCol;
 				return new ZTEsoftGrid(this.options.tableId).init(this.options).loadData(this.options.tableData);
			}
	};
	/**
	 * 表格新增行方法
	 * 表格列需要设ITEM_ID列为key
	 * 隐藏列ITEM_DATA,用于保存数据
	 * ACTION 列作为操作列
	 * POP类型:
	 * ITEM_DATA:{
	 * 	colCode:{returnValue}
	 * }
	 * ColTypeMap类型：
	 * ITEM_DATA:{
	 * 	colCode:{
			OPER:'',
			VALUE:'',
			VAL_NAME:''
			}
	 * }
	 */
	DynamicTable={
		OPER_SINGLE_SEL:',==,<,>,>=,<=,',
		OPER_MULTI_SEL:',IN,!=,', 
		MULTI_SPLIT_CHAR:',', 
		ColTypeMap:{
			T:{
				showName:'Text',isShowEX:false,
				html:'<input class="input dt-ctrl" />',
				ins:function(ins,id,obj){return ins.textIns(id,obj);}
			},
			D:{
				showName:'Date',isShowEX:false,
				html:'<input class="input dt-ctrl" />',
				ins:function(ins,id,obj){return ins.dateIns(id,obj);}
			},
			L:{
				showName:'List',isShowEX:true,
				html:'<select class="select dt-ctrl"></select>',
				ins:function(ins,id,obj){return ins.listIns(id,obj);}
			},
			M:{
				showName:'Mutil',isShowEX:true,
				html:'<select class="select dt-ctrl" multiple="multiple" size="5"></select>',
				ins:function(ins,id,obj){return ins.multiIns(id,obj);}
			},
			R:{
				showName:'Tree',isShowEX:true,
				html:'<div class="dt-ctrl" readonly="readonly"></div>',
				ins:function(ins,id,obj){return ins.treeIns(id,obj);}
			},
			B:{
				showName:'Between',isShowEX:true,
				html:'',
				ins:function(ins,id,obj){return ins.betweenIns(id,obj);}
			}
		},
		getOperHtml:function(id){
			return '<select id="oper_'+id+'" class="select dt-selOper"></select>';
		},
		DiyFuncMap:{
			generateItemObj:function(colObj){return DynamicTable.diyGenerateItemObj(colObj);},
			getControlsValue:function(colObj){return DynamicTable.diyGetValue(colObj);},
			generateControl:function(colObj){return DynamicTable.diyGenerateControl(colObj);},
			initIns:function(colObj){return DynamicTable.diyInitIns(colObj);},
			operChangeBind:function(colObj){return DynamicTable.diyOperChangeBind(colObj);}
		},
		/**
		 * return {html:'',operatorHtml:''}
		 */
		diyGenerateItemObj:function(colObj){},
		diyGetValue:function(){},
		diyGenerateControl:function(){},
		diyInitIns:function(){},
		diyOperChangeBind:function(){},
		getOptions : function(){
			return {
				operWidth:'30%',
				ctrlWidth:'70%',
				tblOptions:{
					delCol:true,
					delOptions:{
						delFunc:'',
						delBeforeFunc:'',
						delIcon:"ui-icon-trash"
					}
				}
			};
		},
		/**
		 * 
	 	 * 按字段类型的初始化方法
		 * 入参cols:[],
		 * tblInfo:表格参数对象
		 * {
		 *  tblId:表格ID（必填）,
		 *  initData:初始化数据（以colCode为key）,
		 *  addObj:表格新增按钮的jquery对象，不传则需手动调用新增方法addTblItem({tblId:''}),
		 *  saveObj:保存按钮jquery对象，不传则需手动调用保存方法saveTblInfo({tblId:''}),
		 *  editObj:编辑按钮jquery对象，不传则需手动调用方法toEditTbl({tblId:''})
		 *  }
		 *  
		 * cols: key:
		 * 		colName,
		 * 		colCode 列的唯一编码，传入colModel的name 值,
		 * 		type(ColTypeMap/POP),
		 * 		colId 作为生成控件id的特殊标识符,
		 * 		hideOper:boolean(是否去除操作符，默认false),
		 * 		POP_INIT(POP类型必须字段,如果传openUrl,则不考虑initPopEdit 等重数组参数，以iframe形式弹出url
		 * 			KEY:showClear,title,openUrl,width,height,
		 * 				customOption :初始化参数，用于openUrl 和 数组参数,
		 * 				needCB:是否需要调用默认回调方法 true/false
		 * 				initPopEdit[],initIframe[],initInnerPage[]...),
		 * 		customData(自定义数据源，以[{ID:'',NAME:''}] 形式保存),
		 * 		validData(className,isRequire)验证对象
		 * 		operatorList(操作符以'==,!=,<'形式)
		 * 		customOption(列扩展参数)
		 */
		init : function(cols,tblInfo,options){
			var ds = {};
			if(!this.dataSource){
				this.dataSource = {};
			}
			this.options = $.extend(true,this.getOptions(),options);
			var self = this;
			var addObj = tblInfo.addObj;
			var saveObj = tblInfo.saveObj;
			var editObj = tblInfo.editObj;
			$.each(cols,function(i,obj){
				ds[obj.colCode] = obj;
				if(obj.type == 'DIY' && !obj.diyFunc){
					obj.diyFunc = function(){};
				}
				if(obj.customData){
					ds[obj.colCode].mapData={};
					$.each(obj.customData,function(j,jtem){
						ds[obj.colCode].mapData[jtem.ID] = jtem.NAME;
					});
				}
			});
			this.dataSource[tblInfo.tblId] = ds;
			//绑定操作符改变方法
			this.operChangeBind(tblInfo);
			//绑定删除行方法
			this.delItemFuncBind(tblInfo);
			var bindName = 'dt_'+tblInfo.tblId;
			if(addObj){
				var addBindName = 'click.'+bindName+'_addclick';
				addObj.unbind(addBindName);
				addObj.bind(addBindName,function(){
					self.addTblItem(tblInfo);
					});
			}
			if(saveObj){
				var saveBindName = 'click.'+bindName+'_saveclick';
				saveObj.unbind(saveBindName);
				saveObj.bind(saveBindName,function(){self.saveTblInfo(tblInfo);});
				var eventArr =$._data(saveObj[0],'events')['click'];
				var last = eventArr.pop();
				eventArr.unshift(last);
//				console.log(eventArr.length);
			}
			if(editObj){
				var editBindName = 'click.'+bindName+'_editclick';
				editObj.unbind(editBindName);
				editObj.bind(editBindName,function(){self.toEditTbl(tblInfo);});
			}
			return this;
		},
		delItemFuncBind : function(tblInfo){
			$('.ui-inline-del',$('#'+tblInfo.tblId)).live('click',function(){
				var $tr = $(this).closest('tr');
				window[tblInfo.tblId].delRowData($tr.attr('id'));
			});
		},
		operChangeBind :function(tblInfo){
			var self = this;
			var $chgTar = $('.spanOper',$('#'+tblInfo.tblId));
			$chgTar.die('change');
			$chgTar.live('change',function(){
				var $spanCol = $(this).next();
				var oper = $(this).children('.dt-selOper').val();
				if(oper == 'ALL' ){
					$spanCol.hide();
					return ;
				}
				$spanCol.show();
				var colCode = $spanCol.attr('colCode');
				var ctrlId =  $spanCol.attr('ctrlId');
				var colObj = self.dataSource[tblInfo.tblId][colCode];
				colObj.tblId = tblInfo.tblId;//将表ID放入列属性中方便传递
				var type = colObj.type;
				var tempOper = ','+oper+',';
				var multiselect = false;
				if(self.OPER_MULTI_SEL.indexOf(tempOper)>=0){
					multiselect = true;
				}
				if(type == 'M'){
					$spanCol.text('');
					if(multiselect){
						//多选
						var $temphtml = self.generateControls(colObj,ctrlId,'M');
						$spanCol.append($temphtml);
						self.ColTypeMap[colObj.type].ins(self,ctrlId,colObj);
					}
					else{
						//单选
						var $temphtml = self.generateControls(colObj,ctrlId,'L');
						$spanCol.append($temphtml);
						self.ColTypeMap['L'].ins(self,ctrlId,colObj);
					}
				}
				else if(type == 'DIY'){
					var params={};
					colObj.diyFunc.call(self,'operChangeBind',params);
				}
				else {
					//非多选框不需要切换控件
					if('' == $spanCol.html()){
						var $temphtml = self.generateControls(colObj,ctrlId,colObj.type);
						$spanCol.append($temphtml);
						self.ColTypeMap[colObj.type].ins(self,ctrlId,colObj);
					}
					else{
						$spanCol.show();
					}
					if(type=='R'){
						//树形控件需要传参
						var val =window[ctrlId].getValue();
						val.multiselect = multiselect;
						window[ctrlId].setValue(val);
						window[ctrlId].dialog.setInitValue(val);
					}
				}

			});
		},
		/**
		 * colObj：列信息，同表格
		 * targetId:生成控件容器id
		 * 返回控件ID
		 */
		generateSingleObj : function(colObj,targetId){
			var itemObj = this.generateItemObj([colObj],{ITEM_ID:''},'');
			var $html = $(itemObj[colObj.colCode]);
			var ctrlId ='dtCtrlId_'+targetId;
			if(colObj.colId){
				ctrlId ='dtCtrlId_'+ colObj.colId;
			}
			var $spanCon = $html.filter('span[class^=spanControl]');
			$spanCon.attr('ctrlId',ctrlId);
			$html.find('.dt-selOper').attr('id','dtOper_'+targetId);
			$html.find('.dt-ctrl').attr('id',ctrlId);
			$('#'+targetId).empty().append($html);
			return ctrlId;
		},
		generateItemObj : function(cols,itemObj,tblId){
			var self = this;
			if(!cols){
				return null;
			}
			$.each(cols,function(i,obj){
				var html = '';
				var operatorHtml='';
				var hideOper = obj.hideOper;
				var operatorList = obj.operatorList;
				var specialStr = obj.colId.replace(/\s/g,'');
				var specialId = 'row_'+itemObj.ITEM_ID+'_'+tblId+'_' + specialStr ;
				var ctrlId = 'ctrl_'+specialId;
				var validData = obj.validData;
				if(obj.type=='DIY'){
					//自定义控件只生成span
					var params ={specialStr : specialStr,ctrlId:ctrlId,obj:obj};
					var htmlObj = obj.diyFunc.call(self,'generateItemObj',params);
					if(htmlObj){
						operatorHtml = htmlObj.operatorHtml;
						html = htmlObj.html;
					}
				}
				else if(obj.type=='POP'){
					var $temphtml = $('<div class="dt-ctrl" readonly="readonly"></div>');
					$temphtml.prop('id',ctrlId);
					if(validData && validData.className){
						$temphtml.addClass(validData.className);
					}
					html = $temphtml[0].outerHTML;
				}
				else{
					if(!self.ColTypeMap[obj.type].html){
						return true;
					}
					if(operatorList && !hideOper){
						//初始化操作符
						operatorHtml = self.getOperHtml(specialId);
					}
					else{
						var $temphtml = self.generateControls(obj,ctrlId,obj.type);
						html = $temphtml[0].outerHTML;//+$midHtml[0].outerHTML+$temphtml2[0].outerHTML;
					}
				}
				var tdEndStr = '';
				if(operatorHtml){
					tdEndStr ='<span class="spanOper">'+operatorHtml+'</span>'
								 +'<span class="spanControlAfOper" ctrlId="'+ctrlId
									+'" colCode="'+obj.colCode
									+'">'+html+'</span>';
				}
				else{
					tdEndStr = '<span class="spanControl" ctrlId="'+ctrlId
						+'" colCode="'+obj.colCode
						+'">'+html+'</span>';
				}
				itemObj[obj.colCode] = tdEndStr;
			});
			return itemObj;
		},
		setStyle : function(tblInfo){
			var options = this.options;
			$('.spanOper').css({
				float:'left',
				width:options.operWidth
			});
			$('.spanControlAfOper').css({
				float:'left',
				width:options.ctrlWidth
			});
			$('.spanControl').css({
				float:'left',
				width:'98%'
			});
		},
		addTblItem : function(tblInfo){
			var newId = '';
			var tblObj = window[tblInfo.tblId];
			newId = tblObj.getRowData().length +1;
			var itemObj={};
			itemObj.ITEM_ID = newId;
			var cols = this.dataSource[tblInfo.tblId];
			var newItem = this.generateItemObj(cols,itemObj,tblInfo.tblId);
			tblObj.addRowData(newItem);
			var $tbl = $('#'+tblInfo.tblId);
			//隐藏修改图标
			this.cleanOrgin($tbl);
			//初始化控件
			var $tr = $('#'+newId,$tbl);
			this.initIns($tr);
			//初始化初始值
			this.initItemVal($tr,tblInfo.initData);
			//设置样式
			this.setStyle(tblInfo);
		},
		/**
		 * 保存控件信息到行上（ITEM_DATA）
		 */
		saveTblInfo : function(tblInfo){
			if(!this.dataSource){
				return ;
			}
			var self = this;
			var tblId = tblInfo ? tblInfo.tblId :''; 
			if(tblId){
				this.saveSingleTbl(tblId);
			}
			else{
				$.each(this.dataSource,function(key,obj){
					self.saveSingleTbl(key);
				});
			}
		},
		saveSingleTbl : function(tblId){
			var tblObj = window[tblId];
			var $trs =  $('tr',$('#'+tblId));
			var self = this;
			$trs.each(function(){
				var $spanCons = $('[class^=spanControl]',$(this));
				if($spanCons.length === 0){
					return true;
				}
				var itemObj = tblObj.getRowData($(this).prop('id'));
				var itemData =itemObj.ITEM_DATA;
				if(!itemData){
					itemData = {};
				}
				$spanCons.each(function(){
					var colCode = $(this).attr('colCode');
					var type = self.dataSource[tblId][colCode].type;
					itemData[colCode] = self.getControlsValue($(this),type);
				});
				itemObj.ITEM_DATA = itemData;
				tblObj.modRowData(itemObj);
			});
		},
		/**
		 * 换到表格编辑状态，数据从ITEM_DATA上取
		 */
		toEditTbl : function(tblInfo){
			if(!this.dataSource){
				return ;
			}
			var self = this;
			var tblId = tblInfo ? tblInfo.tblId :''; 
			if(tblId){
				this.toEditSingleTbl(tblId,this.dataSource[tblId]);
			}
			else{
				$.each(this.dataSource,function(tblId,cols){
					self.toEditSingleTbl(tblId,cols);
					//设置样式
					self.setStyle({tblId:tblId});
				});
			}
		},
		toEditSingleTbl : function(tblId,cols){
			var tblObj = window[tblId];
			var self = this;
			if(tblObj.getRowData()){
				$.each(tblObj.getRowData(),function(i,item){
					var itemObj = self.generateItemObj(cols,item,tblId);
					tblObj.modRowData(itemObj);
					var $tbl = $('#'+tblId);
					//隐藏修改图标
					self.cleanOrgin($tbl);
					//初始化控件
					var $tr = $('#'+itemObj.ITEM_ID,$tbl);
					self.initIns($tr);
					//初始化值
					self.initItemVal($tr);
				});
			}
		},
		/**
		 * 初始化行数据
		 */
		initItemVal : function($tr,itemData){
			var $spanCtrl = $('[class^=spanControl]',$tr);
			var tblId = $tr.parents('table').attr('id');
			var tblObj= window[tblId];
			if(!itemData){
				itemData = tblObj.getRowData($tr.attr('id')).ITEM_DATA;
			}
			var self = this;
			$spanCtrl.each(function(){
				var colCode = $(this).attr('colCode');
				var ctrlId = $(this).attr('ctrlId');
				var colObj = self.dataSource[tblId][colCode];
				var colData = itemData ? itemData[colCode]:'';
				if(colObj.type=='DIY'){
					//自定义控件动态初始化
					var params = {$spanCtrl : $(this)};
					colObj.diyFunc.call(self,'initItemVal',params);
				}
				else{
					self._setValue(colData,colObj.type,ctrlId,colObj,$(this));
				}
			});
		},
		_setValue :function(colData,type,ctrlId,colObj,$spanCtrl){
			if(colData){
				if(!type){
					//type:以入参为准，因为控件会发生变化
					type = colObj.type;
				}
				var $ctrlObj = $spanCtrl.find('.dt-ctrl');
				if(type == 'POP'){
					var popObj = window[ctrlId]; 
					var customOpt = colObj.POP_INIT.customOption;
					var newVal = $.extend(true,colData,customOpt);
					popObj.setValue(newVal);
					popObj.dialog.setInitValue(newVal);
				}
				else {
					var ctrlValue =  colData.VALUE||'';
					var ctrlOper =  colData.OPER;
					var tempOper = ','+ ctrlOper + ',';
					var operObj = $spanCtrl.prev().children(':first');
					if(ctrlOper){
						operObj.val(ctrlOper);
					}
//					初始化延迟加载的控件
					if(operObj && $ctrlObj.length === 0){
						operObj.trigger('change');
						$ctrlObj = $spanCtrl.children(':first');
					}
					//多选列表,无操作符或者操作符可为多选的时候初始化控件值
					if(colObj.type=='M' && (!ctrlOper || this.OPER_MULTI_SEL.indexOf(tempOper)>=0)){
						var splitChar = this.MULTI_SPLIT_CHAR;
						var cusOpt = colObj.customOption;
						if(cusOpt && cusOpt.__splitChar){
							splitChar = cusOpt.__splitChar;
						}
						var dataArr= ctrlValue.split(splitChar);
//						window[ctrlId].setValues(dataArr);
						$ctrlObj.val(dataArr);
						return ;
					}
					if(colObj.type == 'R'){
						//树形控件
						var popObj = window[ctrlId]; 
						var customOpt = colObj.POP_INIT.customOption;
						var displayName = colData.VAL_NAME;
						if(displayName){
							var len = displayName.split(',').length;
							if(len>1){
								displayName = len +' Data';
							}
						}
						var newVal = $.extend(true,{
							displayName:displayName
							,VALUE:ctrlValue
							,VAL_NAME:colData.VAL_NAME
						}
						,customOpt);
						popObj.setValue(newVal);
						popObj.dialog.setInitValue(newVal);
					}
					//其他类型
					$ctrlObj.val(ctrlValue);
				}
			}
		},
		_getValue :function(type,$spanCtrl,colObj){
			if(!type){
				//type:以入参为准，因为控件会发生变化
				type = colObj.type;
			}
			var ctrlId = $spanCtrl.attr('ctrlId');
			if(type=='POP'){
				retVal = window[ctrlId].getValue();
			}
			else{
				var $ctrl = $('#'+ctrlId);
				var value = $ctrl.val();
				var $operObj = $spanCtrl.prev().children('.dt-selOper');
				var operator = $operObj.val();
				var valueName =value;
				if(type == 'R'){
					//树形数据单独判断
					var treeRet = window[ctrlId].getValue();
					value = treeRet.VALUE;
					valueName = treeRet.VAL_NAME;
				}
				//未填值或者通配
				if(!value || operator=='ALL'){
					if(operator != 'ALL'){
						operator == '';
					}
					retVal = {
							OPER:operator,
							VALUE:'',
							VAL_NAME:''};
				}else{
//				var specialStr =id.split('_')[1];
					var tempOper = ','+operator+',';
					if(type=='M' && this.OPER_SINGLE_SEL.indexOf(tempOper)>=0){
						//暂时只考虑多选情况
						type ='L';
					}
					//多选下拉框
					if(type=='M'){
						var multiValue ='';
						var multiValueName ='';
						var splitChar = this.MULTI_SPLIT_CHAR;
						var cusOpt = colObj.customOption;
						if(cusOpt && cusOpt.__splitChar){
							splitChar = cusOpt.__splitChar;
						}
						$.each(value,function(i,item){
							multiValue = multiValue+splitChar+item;
							multiValueName = multiValueName+splitChar+colObj.mapData[item];
						});
						if(multiValue){
							multiValue = multiValue.substring(splitChar.length);
							multiValueName = multiValueName.substring(splitChar.length);
						}
						value = multiValue;
						valueName = multiValueName;
					}
					//单选列表
					if(type =='L'){
						valueName = colObj.mapData[value];
					}
					retVal = 
							{
								OPER:operator,
								VALUE:value,
								VAL_NAME:valueName
							};
				}
			}
			return retVal;
		},
		/**
		 * 获取控件的值
		 * $tar: spanControl
		 */
		getControlsValue : function($tar,type){
			var colCode = $tar.attr('colCode');
			var $tbl = $tar.closest('table');
			var tblId = $tbl.attr('id');
			var cols = this.dataSource[tblId];
			var retVal = null;
			if(type == 'DIY'){
				//自定义控件自己传值
				var params = {$spanCtrl : $tar};
				retVal = cols[colCode].diyFunc.call(this,'getControlsValue',params);
			}
			else{
				retVal=this._getValue(type,$tar,cols[colCode]);
			}
			return retVal;
		},
		/**
		 * 获取容器中控件的值
		 * $tar: targetContainer Obj
		 */
		getControlsValueIn : function($tar,type){
			var $spanCtrl = $tar.children('span[class^=spanControl]');
			var colCode = $spanCtrl.attr('colCode');
			var cols = this.dataSource[$tar.attr('id')];
			var retVal=this._getValue(type,$spanCtrl,cols[colCode]);
			return retVal;
		},
		/**
		 * 生成控件
		 */
		generateControls : function(colObj,ctrlId,type){
			if(type == 'DIY'){
				//自定义控件不生成
				var $diyhtml = colObj.diyFunc.call(this,'generateControls');
				return $diyhtml;
			}
			var $temphtml = $(this.ColTypeMap[type].html);
			$temphtml.prop('id',ctrlId);
			return $temphtml;
		},
		/**
		 * 初始化新增行控件
		 */
		initIns : function($tr){
			var $spanCons = $('[class^=spanControl]',$tr);
			var tblId = $tr.closest('table').attr('id');
			var self = this;
			$spanCons.each(function(){
				var colCode = $(this).attr('colCode');
				var colObj = self.dataSource[tblId][colCode];
				if(colObj.operatorList && !colObj.hideOper ){
					var operMap = {};
					var operList = colObj.operatorList.split(',');
					$.each(operList,function(i,item){
						operMap[item] = {showName:item};
					});
					$(this).prev().children('.dt-selOper').initSelect(operMap,true);
					//有操作符时延迟到选择操作符的时候初始化控件
					return true;
				}
				var id  = $(this).children(':first').prop('id');
				colObj.tblId = tblId;//将表ID放入列属性中方便传递
				if(colObj.type=='DIY'){
					//自定义控件动态初始化
					var params = {$spanCtrl : $(this)}; 
					colObj.diyFunc.call(self,'initIns',params);
					return true;
				}
				if(colObj.type=='POP'){
					self.initPop(id,colObj);
					return true;
				}
				self.ColTypeMap[colObj.type].ins(self,id,colObj);
			});
		},
		treeIns :function(id,colObj){
			colObj.POP_INIT = $.extend(true,
					{
						title : Nebula.ResMgr.getString("SELECT")+" "+ colObj.colName,
						openUrl : "nebula/pub/popwin/PopSelTreeData.jsp",
						customOption : {
							initData:colObj.customData
						}
					},
					colObj.POP_INIT
				);
			this.initPop(id,colObj);
		},
		textIns :function(id,colObj){
			var customData = colObj.customData;
			var validData = colObj.validData;
			var $target = $('#'+id);
			if(validData && validData.className){
				$target.addClass(validData.className);
			}
			//绑定数据源
			if(customData && customData.length>0){
				$target.val(customData[0].NAME);
				$target.prop('realValue',customData[0].ID);
				$target.prop('disabled',true);
			}			
		},
		listIns :function(id,colObj){
			var customData = colObj.customData;
			var validData = colObj.validData;
			var $target = $('#'+id);
			if(validData && validData.className){
				$target.addClass(validData.className);
			}
			//绑定数据源
			if(customData){
				var selDataObj = {};
				$.each(customData,function(i,item){
					selDataObj[item.ID] = {showName:item.NAME};
				});
				var option={
						__define:true
						,__plzSel:true
				};
				var colsOpt = colObj.customOption;
				if(!colsOpt){
					colsOpt ={};
				}
				$.extend(option,colsOpt);
				$target.initSelect(selDataObj,option.__define,option.__plzSel,option);
			}
		},
		betweenIns :function(id){
			
		},
		/**
		 * 日期初始化
		 * @param id
		 */
		 dateIns :function(id,colObj){
			var option = {
					showButtonPanel:true,
					showResetButton:false,  
					showTime:false//不显示时间
				};
			if(colObj.customOption){
				$.extend(true,option,colObj.customOption);
			}
			new ZTEsoftDate(id).init(option);
		},
		/**
		 * 多选下拉框初始化
		 * @param id
		 */
		 multiIns : function(id,colObj){
//			var colInfo = this.dataSource[colObj.tblId][colObj.colCode];
			var colInfo = colObj;
			var mutilData = {};
//			$.each(colInfo.customData,function(i,item){
//				mutilData.push({name:item.NAME,value:item.ID});
//			});
			$.each(colInfo.customData,function(i,item){
				mutilData[item.ID] = {showName:item.NAME};
			});
			var className ='';
			var $target = $('#'+id);
			if(colInfo.validData && colInfo.validData.className){
				className = colInfo.validData.className;
				$target.addClass(className);
			}
			var option={
					multiple:true
					,header:true
					,__splitChar:this.MULTI_SPLIT_CHAR
					,__define:true
			};
			var colsOpt = colObj.customOption;
			if(!colsOpt){
				colsOpt ={};
			}
			$.extend(option,colsOpt);
			$target.initSelect(mutilData,option.define,option);
//			new ZTEsoftMultiSelect(id).loadData(mutilData).init(option);
		},
		/**
		 * 弹出框初始化
		 */
		initPop : function(id,obj){
			var popEdit = obj.POP_INIT.initPopEdit;
			var openUrl = obj.POP_INIT.openUrl;
			var title = obj.POP_INIT.title;
			var width = obj.POP_INIT.width||800;
			var height = obj.POP_INIT.height||500;
			var showClear = obj.POP_INIT.showClear;
			var customOption = obj.POP_INIT.customOption;
			var needCB = obj.POP_INIT.needCB;
			title = title? title : Nebula.ResMgr.getString("SELECT");
			//参数默认为true;
			showClear = showClear === false? false:true;
			needCB = needCB === false? false:true;
			if(openUrl){
				popEdit = [{showClear:showClear,imgTitle:title,openUrl:openUrl},{title:title,width:width,height:height}];
			}
			var dialogPro = new Nebula.UI.Dialog(id);
			var self = this;
			var args0 = {
					imgTitle : Nebula.ResMgr.getString("SELECT"),
					showClear : true,
					clearFunc : function(){return self.cleanPOP(id,customOption);},
					cssprop : "input",
					useIframe : true,
					openUrl : ''
				};
			var args1 = {
					title : Nebula.ResMgr.getString("SELECT"),
					width : 800,
					height : 500,
					resizable : false,
					destroyWhenClose : true
				};
			var args2 = function(returnValue){
				return self.selPOPReturn(id,returnValue,customOption);
			};
			if(!needCB){
				args2 =null;
			}
			var argsArr =[args0,args1,args2];
			if(popEdit && popEdit.length>0){
				if(!popEdit[0].openUrl){
					return null;
				}
				$.each(popEdit,function(i,item){
					if(i<2){
						$.extend(argsArr[i],item);
					}
					if(i===2){
						argsArr[2] = function(returnValue){
							item(id,returnValue,customOption);
							if(!needCB){
								return null;
							}
							return self.selPOPReturn(id,returnValue,customOption);
						};
					}
				});
				if(!argsArr[1].buttons){
					var buttons = {};
					//区别按钮方法
					if(argsArr[0].useIframe){
						buttons[$.jqueryUI.dialog.confirmButton] = function() {
							dialogPro.dialog.iframe.okOnClick();
						};

						buttons[$.jqueryUI.dialog.cancelButton] = function() {
							dialogPro.dialog.close();
						};
					}
					else{
						buttons[$.jqueryUI.dialog.confirmButton] = function() {
							okOnClick();
						};

						buttons[$.jqueryUI.dialog.cancelButton] = function() {
							dialogPro.dialog.close();
						};
					}
					argsArr[1].buttons = buttons;
				}
				dialogPro.initPopEdit(argsArr[0],argsArr[1],argsArr[2]);
//				dialogPro.dialog = new TT.UI.Dialog();
				if(customOption){
					dialogPro.setValue(customOption);
					dialogPro.dialog.setInitValue(customOption);
				}
				//不需要框架封装的清除方法，因为可能会清掉追加参数
				if(argsArr[0].showClear){
					var $cleanSpan = $('#'+id).parent().find('.ui-icon-trash');
					$cleanSpan.parent().unbind('click').click(argsArr[0].clearFunc);
//					$cleanSpan.parent().click(argsArr[0].clearFunc);
				}
			}
			return dialogPro;
		},
		/**
		 * @param returnValue
		 * @param id
		 */
		selPOPReturn : function(id,returnValue,customOption){
			var retVal = $.extend(true,{},returnValue,customOption);
			window[id].setValue(retVal);
			window[id].dialog.setInitValue(retVal);
		},
		/**
		 * 只清数据，避免覆盖追加参数
		 */
		cleanPOP : function(id,customOption){
			var popVal = window[id].getValue();
			if(popVal){
				popVal.displayName='';
				popVal.id = '';
				popVal.VALUE = '';
				popVal.value = '';
				popVal.SEL_DATA ={};
				popVal.RETURN_LIST = [];
			}
			window[id].setValue(popVal);
			window[id].dialog.setInitValue(popVal);
		},
		/**
		 * 清理表格框架封装的方法及图标
		 */
		cleanOrgin : function($tbl){
			//隐藏修改图标
			$('.ui-pg-div.ui-inline-edit',$tbl).hide();
			//去除删除原绑定方法
			$('.ui-inline-del',$tbl).removeAttr('onClick');
		},
		cleanData : function(tblId){
			if(tblId && this.dataSource[tblId]){
				delete this.dataSource[tblId];
			}
			else{
				this.dataSource ={};
			}
		},
		inherit : function(){
			
		}
	};
	DynamicTable.inherit.prototype = DynamicTable;
	var $jq ={};
	/**
	 * 
 	 * 按字段类型的初始化方法
	 * 入参cols:[],
	 * tblInfo:表格参数对象
	 * {
	 *  tblId:表格ID（必填）,
	 *  initData:初始化数据（以colCode为key）,
	 *  addObj:表格新增按钮的jquery对象，不传则需手动调用新增方法addTblItem({tblId:''}),
	 *  saveObj:保存按钮jquery对象，不传则需手动调用保存方法saveTblInfo({tblId:''}),
	 *  editObj:编辑按钮jquery对象，不传则需手动调用方法toEditTbl({tblId:''})
	 *  }
	 *  
	 * cols: key:
	 * 		colName,
	 * 		colCode 列的唯一编码，传入colModel的name 值,
	 * 		type(ColTypeMap/POP),
	 * 		colId 作为生成控件id的特殊标识符,
	 * 		hideOper:boolean(是否去除操作符，默认false),
	 * 		POP_INIT(POP类型必须字段,如果传openUrl,则不考虑initPopEdit 等重数组参数，以iframe形式弹出url
	 * 			KEY:showClear,title,openUrl,width,height,
	 * 				customOption :初始化参数，用于openUrl 和 数组参数,
	 * 				needCB:是否需要调用默认回调方法 true/false
	 * 				initPopEdit[],initIframe[],initInnerPage[]...),
	 * 		customData(自定义数据源，以[{ID:'',NAME:''}] 形式保存),
	 * 		validData(className,isRequire)验证对象
	 * 		operatorList(操作符以'==,!=,<'形式)
	 * 		customOption(列扩展参数)
	 */
	$jq.DtInit = function(dtIns,cols,tblInfo,options){
		if(!dtIns || $.isEmptyObject(dtIns)){
			dtIns = $.DtGetIns();
		}
		return dtIns.init(cols,tblInfo,options);
	};
	$jq.DtGetIns = function(){
		return new DynamicTable.inherit();
	};
	$jq.DtToEditTable = function(dtIns,tblId){
		dtIns.toEditTbl({tblId:tblId});
	};
	$jq.DtSaveTable = function(dtIns,tblId){
		dtIns.saveTblInfo({tblId:tblId});
	};
	$jq.DtAddTableItem = function(dtIns,tblId){
		dtIns.addTblItem({tblId:tblId});
	};
	/**
	 * 清除实例内管理的表格，当表格destroy后用到
	 */
	$jq.DtCleanTable = function(dtIns,tblId){
		dtIns.cleanData(tblId);
	};
	/**
	 * 初始化弹出框,可单独使用
	 */
	$jq.DtInitPop = function(dtIns,id,colObj){
		if(!dtIns){
			dtIns = $.DtGetIns();
		}
		dtIns.initPop(id,colObj);
	};
//	$jq.DtSimplePop = function(){
//		$jq.DtInitPop(null,id,)
//	};
	/**
	 * 初始化控件,可单独使用
	 * --在指定id的控件上初始化
	 */
	$jq.DtInitControl = function(dtIns,id,colObj){
		if(!dtIns){
			dtIns = $.DtGetIns();
		}
		dtIns.ColTypeMap[colObj.type].ins(dtIns,id,colObj);
	};
	/**
	 * 初始化控件,可单独使用
	 * --在指定id的容器内初始化
	 * 返回DynamicTable对象实例，调用方法取值的时候需要传此对象
	 */
	$jq.DtInitControlIn = function(dtIns,targetId,colObj){
		if(!dtIns){
			dtIns = $.DtGetIns();
		}
		//储存
		var ds={};
		if(!dtIns.dataSource){
			dtIns.dataSource = {};
		}
		ds[colObj.colCode] = colObj;
		if(colObj.type == 'DIY' && !colObj.diyFunc){
			colObj.diyFunc = function(){};
		}
		if(colObj.customData){
			ds[colObj.colCode].mapData={};
			$.each(colObj.customData,function(j,jtem){
				ds[colObj.colCode].mapData[jtem.ID] = jtem.NAME;
			});
		}
		dtIns.dataSource[targetId] = ds;
		var ctrlId = dtIns.generateSingleObj(colObj,targetId);
		if(colObj.type == 'POP'){
			dtIns.initPop(ctrlId,colObj);
		}
		else{
			dtIns.ColTypeMap[colObj.type].ins(dtIns,ctrlId,colObj);
		}
		return dtIns;
	};
	/**
	 * 获取指定控件的值
	 * $content：指定控件所在span或者所在容器
	 * (以生成方式为准，比如说在指定容器内生成，则必须用指定容器内方式取值)
	 * 	retVal = 
		{
			OPER:operator,
			VALUE:value,
			VAL_NAME:valueName
		}
		or
		retVal = 
		popwin.getValue();
	 */
	$jq.DtGetVal = function(dtIns,$content,tblId){
		var retVal ={};
		var colCode = $content.attr('colCode');
		if(colCode){
			//获取动态表格内指定span 内的控件值
			retVal = dtIns.getControlsValue($content);
		}
		else{
			//获取指定容器内的控件值
			retVal = dtIns.getControlsValueIn($content);
		}
		return retVal;
	};
	/**
	 * 设置控件值，colData 需与$.DtGetVal返回值相对应
	 */
	$jq.DtSetVal = function(dtIns,$content,tblId,colData){
		var colCode = $content.attr('colCode');
		var ctrlId =  $content.attr('ctrlId');
		var srcKey = tblId;
		var $spanCtrl = $content;
		if(!colCode){
			//设置指定容器内的控件值
			$spanCtrl = $content.children('span[class^=spanControl]');
			ctrlId = $spanCtrl.attr('ctrlId');
			colCode = $spanCtrl.attr('colCode');
			srcKey = $content.attr('id'); 
		}
		var cols = dtIns.dataSource[srcKey];
		var colObj = cols[colCode];
		dtIns._setValue(colData,colObj.type,ctrlId,colObj,$spanCtrl);
	};
	$.extend($jq);
})(jQuery);